﻿using System;
using System.Collections.Generic;
using System.Text;
using Evl.Data.ModelBase;
using Evl.Data.EventArgs;

namespace Evl.Data.Query
{
    public class JoinQuery
    {
        public Dictionary<object, String> ObjAsName = new Dictionary<object, string>();
        public Stack<TableInfo> StaTables = new Stack<TableInfo>();

        public ElvModelBase MainObj{get;set;}
        public String StrSql;

        public JoinQuery(Evl.Data.ModelBase.ElvModelBase modelbase)
        {
            MainObj = modelbase;
            modelbase.PropertyGetting += new EventHandler<PropertyGettingEventArgs>(e_PropertyGetting);
            //创建初始SQL语句

            StrSql = @" SELECT * FROM [" + modelbase.TableName + "] AS " + GetTableAsName(MainObj) + " ";
        }


        protected void e_PropertyGetting(object Sender, PropertyGettingEventArgs e)
        {
            ElvModelBase Entity = (ElvModelBase)Sender;
            //添加到别名对象字典中
            ObjAsName.Add(Entity, "T" + ObjAsName.Count.ToString());

            TableInfo info = new TableInfo();
            info.Entity = Entity;
            info.TableName = Entity.TableName;
            info.FiledName = e.PropertyName;
            info.TableAsName = GetTableAsName(Entity);

            //添加在堆栈中
            StaTables.Push(info);
        }

        /// <summary>
        /// 从别名对象字典中取出对应的别名
        /// </summary>
        /// <param name="Entity">对应的对象</param>
        /// <returns></returns>
        public String GetTableAsName(ElvModelBase Entity)
        {
            foreach (KeyValuePair<object, string> item in ObjAsName)
            {
                if (item.Key.Equals(Entity))
                {
                    return item.Value;
                }
            }
            return String.Empty;
        }


    }

}
